package com.zzy.study.socketANDnio;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient {

	private static final int prot = 9111;
	private Socket socket;
	private DataInputStream				in;
	private DataOutputStream			out;
	private static byte[] buffer = "hellffffffffffochina".getBytes();
	
	public static void main(String[] args) throws InterruptedException {
		for(int i=1; i<=1; i++) {
			new SocketClient().send(i);
		}
	}
	
	public SocketClient() {
		try {
			socket = new Socket("localhost", prot);
			
			this.out = new DataOutputStream(socket.getOutputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void send(int i) {
		try {
			out.writeInt(buffer.length);
			out.write(buffer, 0, buffer.length);
			
			this.in = new DataInputStream(socket.getInputStream());
			System.out.println(readData(in));
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				out.close();
				in.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private static String readData(InputStream in) throws IOException {
		
		DataInputStream dataIn = new DataInputStream(in);
		int length = dataIn.readInt();
		
		StringBuffer sb = new StringBuffer();
		int position = 0;
		byte[] buffer = new byte[10];
		int hasRead = 0;
		
		while((position = dataIn.read(buffer, 0, buffer.length)) != -1) {
			sb.append(new String(buffer, 0, position));
			hasRead += position;
			if(hasRead == length) {
				break;
			}
		}
		return sb.toString();
	}

}
